// frontend/Login.java
package frontend;

import service.DatabaseManager;
import service.Login.LoginResult;
import service.Login.LoginService;
import frontend.admin.LabelManagement;
import frontend.user.UserInterface;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;

public class Login extends JFrame {
    private JTextField userText;
    private JPasswordField passwordText;
    private final LoginService loginService;

    public Login() throws Exception {
        // 初始化服务层
        this.loginService = new LoginService(DatabaseManager.getInstance());
        initialize();
    }

    private void initialize() {
        setTitle("健康科普信息系统 - 登录");
        setSize(800, 600);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLocationRelativeTo(null);

        JPanel mainPanel = new JPanel(new BorderLayout(20, 20));
        mainPanel.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));

        // 恢复原始左上角表情包
        mainPanel.add(createEmoticonPanel("src/main/resources/smile.png", true), BorderLayout.NORTH);

        // 恢复原始右下角表情包（非底部面板）
        mainPanel.add(createEmoticonPanel("src/main/resources/lay.png", false), BorderLayout.SOUTH);

        // 中央表单面板
        mainPanel.add(createFormPanel(), BorderLayout.CENTER);

        add(mainPanel);
        setVisible(true);
    }

    // 创建表情包面板
    private JPanel createEmoticonPanel(String imagePath, boolean isLeft) {
        JPanel panel = new JPanel(new FlowLayout(
                isLeft ? FlowLayout.LEFT : FlowLayout.RIGHT
        ));

        try {
            ImageIcon icon = new ImageIcon(imagePath);
            Image image = icon.getImage().getScaledInstance(100, 100, Image.SCALE_SMOOTH);
            panel.add(new JLabel(new ImageIcon(image)));
        } catch (Exception e) {
            panel.add(new JLabel(isLeft ? "左上角表情包加载失败" : "右下角表情包加载失败"));
        }

        return panel;
    }

    // 创建表单面板
    private JPanel createFormPanel() {
        JPanel panel = new JPanel(new GridBagLayout());
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.insets = new Insets(10, 10, 10, 10);

        // 标题
        JLabel titleLabel = new JLabel("用户登录");
        titleLabel.setFont(new Font("微软雅黑", Font.BOLD, 24));
        gbc.gridx = 0;
        gbc.gridy = 0;
        gbc.gridwidth = 2;
        gbc.anchor = GridBagConstraints.CENTER;
        panel.add(titleLabel, gbc);

        // 表单容器
        JPanel formContainer = new JPanel(new GridBagLayout());
        GridBagConstraints formGbc = new GridBagConstraints();
        formGbc.insets = new Insets(10, 10, 10, 10);

        // 用户名输入
        formGbc.gridx = 0;
        formGbc.gridy = 0;
        formGbc.anchor = GridBagConstraints.EAST;
        formContainer.add(new JLabel("用户名:"), formGbc);

        userText = new JTextField(15);
        formGbc.gridx = 1;
        formGbc.anchor = GridBagConstraints.WEST;
        formContainer.add(userText, formGbc);

        // 密码输入
        formGbc.gridx = 0;
        formGbc.gridy = 1;
        formGbc.anchor = GridBagConstraints.EAST;
        formContainer.add(new JLabel("密码:"), formGbc);

        passwordText = new JPasswordField(15);
        formGbc.gridx = 1;
        formGbc.anchor = GridBagConstraints.WEST;
        formContainer.add(passwordText, formGbc);

        // 按钮
        JButton loginButton = new JButton("登录");
        JButton registerButton = new JButton("注册");

        formGbc.gridx = 0;
        formGbc.gridy = 2;
        formGbc.anchor = GridBagConstraints.CENTER;
        formContainer.add(loginButton, formGbc);

        formGbc.gridx = 1;
        formContainer.add(registerButton, formGbc);

        // 添加表单容器
        gbc.gridy = 1;
        panel.add(formContainer, gbc);

        // 事件绑定
        loginButton.addActionListener(this::handleLogin);
        registerButton.addActionListener(e -> {
            dispose();
            new Register().setVisible(true);
        });

        return panel;
    }

    // 创建底部面板
    private JPanel createBottomPanel() {
        JPanel panel = new JPanel(new FlowLayout(FlowLayout.CENTER));
        panel.add(new JLabel("© 2023 健康科普信息系统 v1.0"));
        return panel;
    }

    // 处理登录事件
    private void handleLogin(ActionEvent e) {
        String username = userText.getText();
        String password = new String(passwordText.getPassword());

        LoginResult result = loginService.authenticate(username, password);

        switch (result.getStatus()) {
            case SUCCESS:
                handleSuccessfulLogin(username, result.getUserPermission());
                break;
            case INVALID_CREDENTIALS:
            case PERMISSION_DENIED:
                JOptionPane.showMessageDialog(
                        this,
                        result.getErrorMessage(),
                        "登录失败",
                        JOptionPane.ERROR_MESSAGE
                );
                break;
            case ERROR:
                JOptionPane.showMessageDialog(
                        this,
                        result.getErrorMessage(),
                        "系统错误",
                        JOptionPane.ERROR_MESSAGE
                );
                break;
        }
    }

    // 处理成功登录
    private void handleSuccessfulLogin(String username, int permission) {
        dispose();

        if (permission == 755) {
            SwingUtilities.invokeLater(() -> {
                try {
                    new UserInterface().setVisible(true);
                } catch (Exception ex) {
                    throw new RuntimeException(ex);
                }
            });
        } else if (permission == 777) {
            SwingUtilities.invokeLater(() -> new LabelManagement().setVisible(true));
        }
    }
}
